#运行之前保证几点:
# 1.县界图层已经修复datasource,要保证在图层顺序的倒数第二的位置
# 结果会放到该mxd文件夹下的mdb中,名字是日期时间戳
import os
import os.path
import time
import string
import arcpy
import arcpy.da

outTableFolderPath = None
#outTableFolderPath=u"H:\\E\山洪灾害\\审核汇集实施\\审核过程数据\\鹤山市\\20160420164014\\GDB.mdb\\OutOfBound"


mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd,"*")[0]
#所有的图层
layers = arcpy.mapping.ListLayers(mxd,"",df)
#县界图层,要保证在倒数第二的位置
BouaLy = layers[len(layers)-2]
BOUA = None
#得到县界的shape
with arcpy.da.SearchCursor(BouaLy, ["SHAPE@"]) as cursor:
    for row in cursor:
        BOUA = row[0]
#移除县界图层
layers.remove(BouaLy)


#先做一个空dictionary 用来存储错误
dict = {}
for lyr in layers :
    if lyr.isBroken == False :
        print lyr.name
        dict[lyr.name] = []
        #逐行做对比
        with arcpy.da.SearchCursor(lyr, ["SHAPE@","OID@"]) as cursor:
            for row in cursor:
                cp = row[0]
                if(BOUA.contains(cp) == False):
                    print("{0}: {1}".format(lyr.name, row[1]))
                    dict[lyr.name].append(row[1])
print dict
#遍历dictionary,将重复的数据输出到新的mdb中
#在指定的目录新建一个个人数据库,用来保存结果.
if(outTableFolderPath == None):
    outTableFolderPath = os.path.dirname(mxd.filePath)
#根据时间生成一个新的个人数据库
newMdb= time.strftime("%Y%m%d%H%M%S")+".mdb"
print newMdb
arcpy.CreatePersonalGDB_management(outTableFolderPath,newMdb)
#生成结果的表的插入游标
#c = arcpy.da.InsertCursor(outTablePath,("lyrName", "OID"))
for k in dict:
    oids=dict.get(k)
    if len(oids) == 0:
        continue
    templateLy = arcpy.mapping.ListLayers(mxd,k,df)[0]
    #arcpy.CreateFeatureclass_management(outTableFolderPath + "\\" + newMdb,k,'',templateLy)
    #将所有的数据拷贝到新的mdb,然后删除正确的,不就剩下不正确的了吗???
    arcpy.Copy_management(templateLy.dataSource, outTableFolderPath + "\\" + newMdb +"\\"+k)
    #c = arcpy.da.InsertCursor(outTableFolderPath + "\\" + newMdb +"\\"+k,"*")
    where_clause="OBJECTID not in (" + ','.join(map(str,oids)) +")"
    print ("{0}: {1}".format(templateLy.name, where_clause))
    with arcpy.da.UpdateCursor(outTableFolderPath + "\\" + newMdb +"\\"+k, "*", where_clause) as cursor:
            for row in cursor:
                cursor.deleteRow ()
#完美收官
